package com.lilicould.controller;

import com.google.gson.Gson;
import com.lilicould.entity.Colleges;
import com.lilicould.service.CollegeService;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/college/*")
public class CollegeController extends BaseServlet{
    public void listAll(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("application/json;charset:utf-8");
        PrintWriter out = resp.getWriter();
        String result = new CollegeService().getAllCollege();

        // 若不为空，说明成功获取到学院信息，则返回200状态码以及结果
        if (result != null) {
            resp.setStatus(HttpServletResponse.SC_OK);
            out.write(result);
        }else {
            // 若为空，则返回404状态码
            resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }

    }

    public void add(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("application/json;charset:utf-8");

        // 获取请求中的json数据并解析成Colleges对象
        Gson gson = new Gson();
        Colleges colleges = gson.fromJson(req.getReader().readLine(), Colleges.class);

        // 调用服务层添加学院信息
        String result = new CollegeService().addCollege(colleges);
        if (result != null) {
            // 若返回结果不为空，则说明添加失败，返回400状态码并返回错误信息
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            PrintWriter out = resp.getWriter();
            // 将错误信息返回给前端
            out.write(gson.toJson(result));
        }else {
            // 若返回结果为空，则说明添加成功，返回200状态码
            resp.setStatus(HttpServletResponse.SC_OK);
        }
    }

    public void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("application/json;charset:utf-8");
        String collegeCode = req.getParameter("collegeCode");

        // 调用服务层删除学院信息
        String result = new CollegeService().deleteCollege(collegeCode);

        if (result != null) {
            // 若返回结果不为空，则说明删除失败，返回400状态码并返回错误信息
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            PrintWriter out = resp.getWriter();
            out.write(new Gson().toJson(result));
        } else {
            // 若返回结果为空，则说明删除成功，返回200状态码
            resp.setStatus(HttpServletResponse.SC_OK);
        }
    }
}
